import 'package:lib_bt/send/PackageInterface.dart';
import 'package:lib_util/ByteUtils.dart';
import 'package:lib_util/CrcUtils.dart';
import '../UUIDConfig.dart';

///color系列数据包实现类
class ColorPackageImpl extends PackageInterface {
  //创建一个简单的数据包(不需要分包)
  static PackageInterface createSimplePackage(List<int> header, List<int> data,
      {String? serviceUuid, String? characteristicUuid}) {
    List<int> bytes = header;
    bytes.addAll(ByteUtils.shortToBytes(data.length + 2));
    bytes.addAll(data);
    bytes.addAll(CrcUtils.getShortCheckNum(bytes));
    PackageInterface package = PackageInterface();
    package.data = bytes;
    package.serviceUuid = serviceUuid ?? UUIDConfig.instance.uuid_server;
    package.characteristicUuid = characteristicUuid ?? UUIDConfig.instance.uuid_write_1;
    return package;
  }

  //分包
  static List<PackageInterface> createPackage(List<int> data, int mtu) {
    mtu -= 20;
    List<PackageInterface> packages = [];

    //分包数据实际能用到大小(mtu-协议相关占用)
    int dataSize = mtu - 12;

    //分割数据
    List<List<int>> dataList = manualChunk(data, dataSize);
    //组装

    for (int i = 0; i < dataList.length; i++) {
      var dataList2 = dataList[i];
      packages.add(createSimplePackage(
          [0x54, 0x00], ByteUtils.int2Byte(i) + ByteUtils.shortToBytes(dataList2.length) + dataList2,
          serviceUuid: UUIDConfig.instance.uuid_server, characteristicUuid: UUIDConfig.instance.uuid_write_2));
    }
    //结束包
    packages.add(createSimplePackage([0x54, 0x01], [0x01],
        serviceUuid: UUIDConfig.instance.uuid_server, characteristicUuid: UUIDConfig.instance.uuid_write_2));
    return packages;
  }

  static List<List<int>> manualChunk(List<int> data, int chunkSize) {
    List<List<int>> result = [];
    for (int i = 0; i < data.length; i += chunkSize) {
      int end = i + chunkSize;
      result.add(data.sublist(i, end > data.length ? data.length : end));
    }
    return result;
  }
}
